/*************************************************************************
	> File Name: oledHex.c
	> Author: 
	> Mail: 
	> Created Time: 2016年12月22日 星期四 20时23分12秒
 ************************************************************************/

#include<stdio.h>
#include <stdlib.h>
#include <string.h>

unsigned char getBit(unsigned char value)
{
    unsigned char res = (value < 128) ? 1 : 0;
    /*printf("%d", res);*/
    return res;
}

int main(int argc, char **argv)
{
    if (argc != 2) {
        printf("usage: %s bmpfile\n", argv[0]);
        return -1;
    }

    FILE *bmp = fopen(argv[1], "rb");
    short bitDepth = 0;
    short bmpHead = 0;

    fread(&bmpHead, 2, 1, bmp);
    if (bmpHead != 0x4d42) {
        printf("not bmp format\n");
        return -1;
    }

    fseek(bmp, 0x1c, SEEK_SET);
    fread(&bitDepth, 2, 1, bmp);
    if (bitDepth != 0x18) {
        printf("%d\n", bitDepth);
        printf("support 24bits bmp only\n");
        return -1;
    }

    int width = 0;
    int height = 0;
    fseek(bmp, 0x12, SEEK_SET);
    fread(&width, sizeof(int), 1, bmp);
    fread(&height, sizeof(int), 1, bmp);
    printf("input file info: \n");
    printf("size = %dx%d\n", width, height);
    int w = width;
    int h = height / 8 + 1;
    int fill = 8 - (height % 8);
    printf("filling %d row\n", fill/2);

    int imgSize = 0;
    fseek(bmp, 0x22, SEEK_SET);
    fread(&imgSize, sizeof(int), 1, bmp);

    unsigned char *buffer = (unsigned char *)malloc(imgSize + fill * w*3);
    memset(buffer, 0xff, imgSize + fill*w*3);
    fseek(bmp, 54, SEEK_SET);
    /*fread(buffer, width * height * 3, 1, bmp);          // 填充在下方*/
    fread(buffer + fill/2 * w *3, imgSize, 1, bmp); // 上下填充
    printf("size %d\n", imgSize);

    int i, j;
    for (i = 0; i < h; ++i) {
        for (j = 0; j < w; ++j) {
            unsigned char byte = 0;
            byte |= getBit(buffer[3*(j + w*(i*8))]);
            byte |= getBit(buffer[3*(j + w*(i*8+1))]) << 1;
            byte |= getBit(buffer[3*(j + w*(i*8+2))]) << 2;
            byte |= getBit(buffer[3*(j + w*(i*8+3))]) << 3;
            byte |= getBit(buffer[3*(j + w*(i*8+4))]) << 4;
            byte |= getBit(buffer[3*(j + w*(i*8+5))]) << 5;
            byte |= getBit(buffer[3*(j + w*(i*8+6))]) << 6;
            byte |= getBit(buffer[3*(j + w*(i*8+7))]) << 7;
            printf("0x%02x", byte);
            printf(", ");
        }
        printf("\n");
    }

    free(buffer);
    fclose(bmp);
    return 0;
}
